#!/usr/bin/python
# -*- coding: utf-8 -*-


import BasicHTTPServiceAPI.BasicHTTPService
import oauth

from error import APIError
from utils import convert_to_utf8_str


def bind_api(**config):
    """function for binding api method"""
    class APIMethod(object):
        """class for representing a api method"""
        url = config.get('url')
        method = config.get('method', 'GET')
        allowed_params = config.get('allowed_params', [])
        require_auth = config.get('require_auth', False)
        SSL = config.get('ssl', False)
        data_type = config.get('data_type', 'model')
        data_format = config.get('data_format', 'json')
        data_list = config.get('data_list', False)

        def __init__(self, api, args, kargs):
            """constructor for APIMethod"""
            self.api = api
            self.params = self.build_params(args, kargs)
            tempbaseUrl = ''
            if self.SSL:
                tempbaseUrl += 'https://'
            else:
                tempbaseUrl += 'http://'
            self.baseUrl = tempbaseUrl + self.api.host + self.url
            if self.require_auth:
                self.params.update(self.build_oauth())
                self.sign_request()

        def build_params(self, args, kargs):
            """build params for api method"""
            params = {}
            for idx, value in enumerate(args):
                try:
                    if type(value) is dict:
                        params.update(value)
                    else:
                        params[self.allowed_params[idx]] = convert_to_utf8_str(value)
                except IndexError:
                    raise APIError('Too many parameters supplied!')
            for k, v in kargs.items():
                if v is None:
                    continue
                if k in params:
                    raise APIError('multiple parameters for %s are supplied!' % k)
                params[k] = convert_to_utf8_str(v)
            return params

        def build_oauth(self):
            """build oauth params for api method"""
            pass

        def sign_request(self):
            """sign the request with HMAC-SHA1"""
            pass

        def execute(self):
            """execute the api method"""
            print self.params
            res = BasicHTTPServiceAPI.BasicHTTPService.basicAPIFetch(self.api.host, self.url, \
                                                 self.params, method=self.method,\
                                                 SSL=self.SSL)
            if res['status'] < '200':
                return self.api.parser.parse(self, res['data'])
            else:
                raise APIError(res['status'])

    def _call(api, *args, **kargs):
        """call api method"""
        method = APIMethod(api, args, kargs)
        return method.execute()

    return _call
